
from demo1.utils import DbConfigUtils
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
import importlib
def reload_jobs(scheduler):
    print("重载任务正在执行")
    scheduler.remove_all_jobs()
    load_jobs_from_db(scheduler)


def load_jobs_from_db(scheduler):
    result = DbConfigUtils.fetchAll("SELECT * FROM scheduled_jobs WHERE enabled = TRUE")
    for row in result:
        job_id = row['id']
        func_name = row['func_name']
        trigger_type = row['trigger_type']

        # 动态导入函数
        module_name, func_name = func_name.rsplit('.', 1)
        module = importlib.import_module(module_name)
        func = getattr(module, func_name)

        # 构建触发器
        if trigger_type == 'cron':
            trigger = CronTrigger(
                hour=row['hour'],
                minute=row['minute'],
                second=row['second'],
                day_of_week=row['day_of_week']
            )
        elif trigger_type == 'interval':
            trigger = IntervalTrigger(seconds=int(row['second']))
        else:
            continue  # 跳过不支持的触发器类型

        # 添加任务
        scheduler.add_job(func=func, trigger=trigger, id=job_id, replace_existing=True)